package com.ruoyi.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.service.UserService;
import com.ruoyi.web.domain.*;
import com.ruoyi.web.mapper.GrCardMapper;
import com.ruoyi.web.mapper.GrUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private GrUserMapper grUserMapper;
    @Resource
    private GrCardMapper grCardMapper;


    @Override
    public IPage<UserPageResponse> userPageList(UserPageRequest request) {
        List<GrCard> grCards = grCardMapper.selectGrCardList(null);
        Map<Integer, GrCard> cardMap = null;
        if(CollectionUtils.isNotEmpty(grCards)){
            cardMap = grCards.stream().collect(Collectors.toMap(GrCard::getId, a -> a, (k1, k2) -> k1));
        }
        Page<UserPageResponse> page = new Page<>(request.getPageNum(), request.getPageSize());
        IPage<UserPageResponse> iPage= grUserMapper.pageList(page, request);
        List<UserPageResponse> records = iPage.getRecords();
        if(CollectionUtils.isNotEmpty(records)){
            for (UserPageResponse record : records) {
                if(record.getCardId() != null){
                    GrCard grCard = cardMap.get(record.getCardId());
                    if(grCard != null){
                        record.setCardName(grCard.getCardName());
                    }
                }
                // 处理时间
                if(record.getLastLoginTime()!= null){
                    record.setLastLoginTimeStr(getTimeByLong(record.getLastLoginTime()));
                }
                if(record.getCreateTime()!= null){
                    record.setCreateTimeStr(getTimeByLong(record.getCreateTime()));
                }
                if(record.getUpdateTime()!= null){
                    record.setUpdateTimeStr(getTimeByLong(record.getUpdateTime()));
                }
            }
        }
        return iPage;
    }

    @Override
    public boolean updateCard(UpdateUserCardRequest request) {
        GrCard grCard = grCardMapper.selectGrCardById(request.getCardId());
        if(grCard != null){
            throw new RuntimeException("该卡不存在");
        }
        GrUserDO grUserDO = grUserMapper.selectById(request.getId());
        if(grUserDO == null){
            throw new RuntimeException("该用户不存在");
        }
        if(request.getValidityEndTime()!=null && request.getValidityEndTime() < System.currentTimeMillis()){
            throw new RuntimeException("有效期不能小于当前时间");
        }else{
            if(request.getValidityEndTime()==null){
                Long lastYear = getLastYear(1);
                grUserDO.setValidityEndTime(lastYear);
            }else{
                grUserDO.setValidityEndTime(request.getValidityEndTime());
            }
        }
        grUserDO.setCardId(request.getCardId());
        int i = grUserMapper.updateById(grUserDO);
        return i > 0;
    }

    public String getTimeByLong(Long time) {
        LocalDateTime dateTime = LocalDateTime.ofInstant(
                Instant.ofEpochMilli(time),
                ZoneId.systemDefault()
        );
        // 定义输出格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化输出
        return dateTime.format(formatter);
    }

    /**
     * 获取当前时间戳一年后的日期
     * @param year
     * @return
     */
    public static Long getLastYear(Integer year){
        // 1. 获取当前LocalDateTime
        LocalDateTime now = LocalDateTime.now();
        // 2. 计算一年后的时间
        LocalDateTime oneYearLater = now.plusYears(year);
        // 3. 转换为时间戳（毫秒）
        return oneYearLater
                .atZone(ZoneId.systemDefault())
                .toInstant()
                .toEpochMilli();
    }

}
